import * as AppClientApis from '@/network/apis/appClient.js';

async function CheckUpdate() {

	let res = await AppClientApis.getart('safety');
	if (res && res.success) {
		 uni.hideLoading();
		if (res.data && res.data[0]) {
		  
			let c = res.data[0];
			let v = await GetVersion();
			if(!v){
			
				uni.showToast({
					title: "暂无更新",
					icon: "none"
				})
				
				return;
				
			}
			//线上版本小于等于当前版本
			if(parseInt(c.version)<=v.versionNo){
				
				uni.showToast({
					title: "暂无更新",
					icon: "none"
				})
				return;
			}
			console.log(parseInt(c.version),v.versionNo,"线上版本小于等于当前版本："+parseInt(c.version)<=v.version);
			if (c.file) {
				uni.showModal({
					title: '更新提示',
					content: '检查到有新版本，是否更新？',
					cancelText: '取消',
					confirmText: "更新",
					success({
						confirm
					}) {
						if (confirm) {
							DownloadPackage(c.file);
						}
					}
				})
			}else{
				uni.showToast({
					title: "暂无更新",
					icon: "none"
				})
			}
		} else {
			uni.showToast({
				title: "暂无更新",
				icon: "none"
			})
		}
	} else {
		uni.showToast({
			title: res.message ? res.message : "请稍后重试",
			icon: "none"
		})
	}
	console.log(res)
	uni.hideLoading();


}

function GetVersion(){
	return new Promise((resolve,reject)=>{
		// #ifdef APP-PLUS
		     // this.currentVersion = plus.runtime.version;
		    plus.runtime.getProperty(plus.runtime.appid,(res)=>{
				console.log(res);
				if(res&&res.version){
					  resolve({
						 version :res.version,
						  versionNo : parseInt(res.version.split('.').join(''))
					  })
				}else{
					resolve(null);
				}
			})
		// #endif
	})
}

function DownloadPackage(url) {
	var showLoading = plus.nativeUI.showWaiting("正在下载", {
		back: "none"
	}); //{back: "none"}用来禁止返回键
	const task = plus.downloader.createDownload(url, {
			timeout: 20
		},
		(res, status) => {
			if (status === 200) {
				plus.runtime.install(res.filename)
			} else {
				showLoading.close();
			}
			console.log(res)
		});
	OnProgress(task, showLoading);
	task.start();
	   
   // setTimeout(()=>{
	  //  task.abort();
	  //  showLoading.close();
	  //  uni.showToast({
	  //  	title: "请稍后重试",
	  //  	icon: "none"
	  //  })
   // },20000)
}

function OnProgress(task, Label) {
	task.addEventListener('statechanged', e => {
		if (e && e.downloadedSize > 0) {
			const progress = ((e.downloadedSize / e.totalSize) * 100).toFixed(2)
			// this.progress.value = progress;
			Label.setTitle("  正在下载" + progress + "%  ");
			if (progress >= 100) {
				plus.nativeUI.closeWaiting();
			}
		}
	}, false)
}

export default{
	CheckUpdate
}